<!--
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-12-18 15:55:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-11-07 09:40:55
 * @FilePath: BarCharts.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <!-- 柱状图组合 -->
    <div class="BarChartsBox" :style="'height:' + Height + 'px;'">
        <!-- tab切换 -->
        <div class="tabBox" ref="centerTabRef2">
            <el-radio-group size="small" v-model="activeName" @change="selectActive">
                <el-radio-button label="1">日均值</el-radio-button>
                <el-radio-button label="2">近30天</el-radio-button>
            </el-radio-group>
        </div>
        <div class="averageBox">均值：{{ averageNum }}{{ Number(activeName) === 1 ? '次' : '千次' }}</div>
        <!-- 图形 -->
        <div id="BarCharts"></div>
    </div>
</template>
<script>
export default {
    name: 'BarCharts',
    props: {
        Height: {
            type: Number,
            default: 0
        },
    },
    data() {
        return {
            activeName: '1',
            barChart: null,
            averageNum: 0,
        }
    },
    mounted() {
        this.getInfo()
        window.addEventListener('resize', () => {
            setTimeout(async () => {
                await this.barChart.resize()
            }, 110)
        })
    },
    methods: {
        async selectActive(val) {
            await this.getInfo()
        },
        // 求数据的平均值
        average(arr) {
            const sum = arr.reduce((a, b) => Number(a) + Number(b), 0);
            const avg = sum / arr.length;
            return avg.toFixed(2); // 保留两位小数
        },
        // 获取数据
        async getInfo() {
            const { data: res } = await this.$http.get(Number(this.activeName) === 1 ? '/TalkScreen/Api/HlPhone/yysCallStateToday' : '/TalkScreen/Api/HlPhone/yysCallStateTotal')
            await this.getChart(res)
        },
        getChart(array) {
            let that = this
            that.barChart = that.$echarts.init(document.getElementById('BarCharts'))
            var dataOne = [] // 有效通话
            var dataTwo = [] // 无效通话
            var dataThird = [] // 异常通话
            var typeList = [] // 运营商类型
            array.forEach((item, index) => {
                dataOne.push(Number(that.activeName) === 1 ? item.successTotalCount : (Number(item.successTotalCount) / 1000).toFixed(2))
                dataTwo.push(Number(that.activeName) === 1 ? item.failTotalCount : (Number(item.failTotalCount) / 1000).toFixed(2))
                dataThird.push(Number(that.activeName) === 1 ? item.shortSuccessCount : (Number(item.shortSuccessCount) / 1000).toFixed(2))
                typeList.push(item.yysName)
            })
            let arrList = [...dataOne, ...dataTwo, ...dataThird]
            that.averageNum = that.average(dataOne)
            // 获取坐标轴刻度最大值
            let maxVal = Number(Math.max(...arrList)) + 10;
            // 获取坐标轴刻度最小值
            let minVal = Number(Math.min(...arrList)) + 10;
            // 计算坐标轴分割间隔
            let interval = Math.floor((maxVal - minVal) / 5);
            let color = ['#1FA4F8', '#F95B00', '#4B5C91']
            var option = {
                color: color,
                title: {
                    text: `单位/${Number(that.activeName) === 1 ? '次' : '千次'}`,
                    top: that.$util.nowSizeWidth(55),
                    left: -5,
                    textStyle: {
                        color: '#FFFFFF',
                        fontSize: that.$util.nowSizeWidth(12),
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: "#fff",
                    extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
                    formatter: function (params) {
                        return (
                            `<span style='font-size: 12px;
                                font-family: Source Han Sans CN, Source Han Sans CN;
                                font-weight: bold;
                                color: #0A1F48;margin-left:-2px;margin-bottom:4px;display:inline-block;'>${params[0].name}</span>` +
                            `<br>` +
                            params
                                .map((item, index) => {
                                    let str = `<span style="display:inline-block;vertical-align: middle;width:8px;height:8px;margin: 0 5px 0 0px;background-color:${color[index]};"></span>`
                                    let seriesNameStr = `<span style="display:inline-block;font-size:12px;vertical-align: middle;">${item.seriesName}</span>`
                                    let value = item.value
                                    let valueStr = `<span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;">${value}${Number(that.activeName) === 1 ? '次' : '千次'}</span>`
                                    return `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
									<span>${str}${seriesNameStr}</span>
									<span>${valueStr}</span>
								</span>`
                                })
                                .join(``)
                        )
                    },
                },
                grid: {
                    left: 0,
                    right: 0,
                    bottom: 0,
                    top: that.$util.nowSizeWidth(86),
                    containLabel: true
                },
                legend: {
                    orient: 'horizontal',
                    icon: 'rect',
                    top: that.$util.nowSizeWidth(22),
                    right: 0,
                    itemWidth: 9,
                    itemHeight: 9,
                    textStyle: {
                        color: '#fff',
                        rich: {
                            a: {
                                verticalAlign: 'middle',
                            },
                        },
                        padding: [2, 0, 0, 0],
                    },
                    data: ['有效通话', '无效通话', '异常通话']
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLine: {
                            lineStyle: {
                                type: 'dashed',
                                color: '#0D3B77',//左边线的颜色
                                width: '1'//坐标线的宽度
                            }
                        },
                        axisLabel: {
                            width: 50, // 设置固定宽度
                            formatter: function (params) {
                                var str = "";                 // 最终拼接成的字符串
                                var paramsLen = params.length;// 获取每项文字的个数
                                var len = 2;                  // 每行能显示的字的个数（根据实际情况自己设置）
                                var rowNumber = 2; // 换行的话，需要显示几行，向上取整
                                if (paramsLen > len) {        //大于设定的len就换行，不大于就不变化
                                    for (var i = 0; i < rowNumber; i++) {
                                        var temp = "";            // 表示每一次截取的字符串
                                        var start = i * len;      // 开始截取的位置
                                        var end = start + len;    // 结束截取的位置
                                        if (i == rowNumber - 1) { // 最后一次不换行
                                            temp = params.substring(start, paramsLen);
                                        } else {                  // 每一次拼接字符串并换行
                                            temp = params.substring(start, end) + "\n";
                                        }
                                        str += temp;              // 最终拼成的字符串
                                    }
                                } else {                      // 给新的字符串赋值
                                    str = params;
                                }
                                return str;                   //返回字符串
                            },
                            textStyle: {
                                color: '#ffffff',//坐标值得具体的颜色
                                fontSize: that.$util.nowSizeWidth(12),
                            },
                            interval: 0
                        },
                        axisTick: false,
                        data: typeList
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        // min: minVal, // 坐标轴刻度最小值。
                        // max: maxVal, // 坐标轴刻度最大值。
                        // interval: interval, // 强制设置坐标轴分割间隔。
                        minInterval: 1,
                        scale: true,
                        axisLine: {
                            lineStyle: {
                                type: 'solid',
                                color: '#2E3950',//左边线的颜色
                                width: '1',//坐标线的宽度
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#e6e6e6',//坐标值得具体的颜色
                            }
                        },
                        axisTick: false,
                        splitLine: {  //坐标轴在grid区域中的分隔线（网格中的横线）
                            show: true,
                            lineStyle: {
                                color: ['#0D3B77'],
                                width: 1,
                                type: 'dashed',
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '有效通话',
                        type: 'bar',
                        activeName: that.activeName,
                        barGap: 0,
                        barWidth: '18%',
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [
                                            {
                                                offset: 0,
                                                color: '#10527C' // 0% 处的颜色
                                            },
                                            {
                                                offset: 1,
                                                color: '#1FA4F8' // 100% 处的颜色
                                            }
                                        ]
                                    }
                                },
                            },
                        },
                        data: dataOne,
                        markLine: {
                            data: [
                                {
                                    name: '平均值',
                                    type: 'average',
                                    yAxis: that.average(dataOne),
                                    lineStyle: {
                                        color: '#4BEEFF',    // 线条颜色
                                        width: 1,       // 线条宽度
                                        type: 'dashed'    // 线条类型，默认为实线，可选：'solid', 'dashed', 'dotted'
                                    },

                                    label: {
                                        // formatter: `均值：${that.average(dataOne)}${Number(that.activeName) === 1 ? '次' : '千次'}`,
                                        fontSize: '0px',
                                        // backgroundColor: 'rgba(44, 95, 196, 1)',
                                        // color: '#ffffff',
                                        // position: 'insideEndTop',
                                        // padding: [0, 10],
                                        // distance: [60, 5], // 设置标签文字的样式
                                        // // width: 72,
                                        // height: 24,
                                        // lineHeight: 22,
                                        // align: 'center',
                                        // borderRadius: 4,
                                    }
                                }
                            ],

                        }
                    },
                    {
                        name: '无效通话',
                        type: 'bar',
                        activeName: that.activeName,
                        barGap: 0,
                        barWidth: '18%',
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [
                                            {
                                                offset: 0,
                                                color: '#7D2E00' // 0% 处的颜色
                                            },
                                            {
                                                offset: 1,
                                                color: '#F95B00' // 100% 处的颜色
                                            }
                                        ]
                                    }
                                },
                            },
                        },
                        data: dataTwo
                    },
                    {
                        name: '异常通话',
                        type: 'bar',
                        barGap: 0,
                        activeName: that.activeName,
                        barWidth: '18%',
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [
                                            {
                                                offset: 0,
                                                color: '#4B5C91' // 0% 处的颜色
                                            },
                                            {
                                                offset: 1,
                                                color: '#4B5C91' // 100% 处的颜色
                                            }
                                        ]
                                    }
                                },
                            },
                        },
                        data: dataThird
                    },
                ]
            }
            that.barChart.setOption(option, true)
        },
    }
}

</script>
<style lang="less" scoped>
.BarChartsBox {
    width: 100%;
    position: relative;

    .tabBox {
        position: absolute;
        top: 20px;
        left: 0px;
        z-index: 999;
    }

    #BarCharts {
        width: 100%;
        height: 100%;
    }

    .averageBox {
        position: absolute;
        top: 25%;
        right: 0px;
        font-size: 12px;
        color: #4BEEFF;
    }
}
</style>